package com.shou.lifecollege.framework.Security.filter;

import cn.hutool.core.util.ObjectUtil;
import com.shou.lifecollege.framework.Common.util.SecurityUtils;
import com.shou.lifecollege.framework.Security.core.TokenManager;
import com.shou.lifecollege.framework.Security.model.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: luotian
 * @Date: 2022/11/24 17:02
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final TokenManager tokenManager;

    public JwtAuthenticationTokenFilter(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        LoginUser loginUser=tokenManager.getLoginUser(request);
        if(ObjectUtil.isNotNull(loginUser)&&ObjectUtil.isNull(SecurityUtils.getAuthentication()))
        {
            tokenManager.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }
}
